package com.ch999.mobileoa.page;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.ch999.mobileoa.R;
import com.ch999.mobileoa.data.UserData;
import com.ch999.mobileoa.request.DataControl;
import com.sda.lib.HttpCore.DataResponse;
import com.sda.lib.util.ACache;
import com.sda.lib.util.Tools;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;

/**
 * Created by scorpio on 15/12/18.
 */
public class LoginActivity extends Activity implements View.OnClickListener{

    @ViewInject(id =R.id.et_name)
    EditText et_name ;
    @ViewInject(id =R.id.et_pwd)
    EditText et_pwd ;
    @ViewInject(id =R.id.btn_login,click = "onClick")
    ImageView btn_login ;

    Context context ;
    String name ,pwd ;

    UserData userData ;

    ProgressDialog dialog ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        context = LoginActivity.this ;
        FinalActivity.initInjectedView(this);

        dialog = new ProgressDialog(context);
        dialog.setMessage("正在登录,请稍后...");


    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.btn_login:
                name = et_name.getText().toString();
                pwd = et_pwd.getText().toString();
                if (Tools.isEmpty(name) || Tools.isEmpty(pwd)){
                    Tools.toast(context,"工号或密码为空,请重新输入");
                }else {
                    dialog.show();
                    Login(name,pwd);
                }
                break;
        }
    }

    /**
     * 登录
     * @param name
     * @param pwd
     */
    private void Login(final String name, String pwd) {
        DataControl.Login(context, name, pwd, new DataResponse() {
            @Override
            public void onSucc(Object response) {
                dialog.dismiss();
                userData = (UserData) response;

                // 保存用户信息15天有效期
                ACache.get(context).put("UserData",userData,15 * ACache.TIME_DAY);
                finish();
            }

            @Override
            public void onFail(String error) {
                dialog.dismiss();
                Tools.toast(context,error);
            }
        });
    }
}
